// redPacket/pages/openGroup.js
const service = require('../openGroup/openGroupService.js');
const utilService = require('../../../utils/utilService.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    inviteUserId: '', //分享的邀请者id
    flag: 0, // 分享链接标志
    shareMsg: null,
    countDownHour: '00',
    countDownMinute: '00',
    countDownSecond: '00',
    items: [],
    status: -1, //0拼团中(团长)1拼团失败2拼团完成3参与4未参与）
    reason: "该团已超时，再去开团吧",
    timeCounting: false,
    groupBuyGoodsVos: [], //拼参团列
    groupDetail: '', //拼团详情
    groupBuyId: '', //拼团id
    groupBuyUserId: null, //拼团人id
    grouperId: '团长id',
    second: 0, //剩余时间
    userUrls: [], //用户头像
    addressData: null,
    redPacketData: null,
    scrollLeft: 0,
    scrollWidth: 0,
    page: 0,
    nextShow: false,
    preShow: false,
    options:null,
    joinStatus: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    var rpx = 542;
    var systemInfo = wx.getSystemInfoSync();
    var scrollWidth = rpx / 750 * systemInfo.windowWidth;
    this.setData({
      scrollWidth: scrollWidth,
      options: options
    })
    console.log("options:" + JSON.stringify(options));
    var self = this;
    //授权
    self.authAlert = self.selectComponent("#authAlert");
    self.authAlert.bindCatch()
    app.loginPromise.then(() => {
      self.getShareMessage(21)
      if (options.flag == 1 && options.userId != app.globalData.userId) {
        self.setData({
          groupBuyUserId: options.groupBuyUserId,
          groupBuyId: options.groupBuyId,
          inviteUserId: options.userId,
          grouperId: options.grouperId
        })
        self.joinGroup()
      } else {
        self.setData({
          inviteUserId: app.globalData.userId
        })
        self.loadRedPacketDetail()
      }
    });
  },

  /**
   * 点击授权
   */
  authSuccess() {
    var options = this.data.options;
    this.getShareMessage(21);
    if (options.flag == 1) {
      this.setData({
        groupBuyUserId: options.groupBuyUserId,
        groupBuyId: options.groupBuyId,
        inviteUserId: options.userId,
        grouperId: options.grouperId
      })
      this.joinGroup()
    } else {
      this.setData({
        inviteUserId: app.globalData.userId
      })
      this.loadRedPacketDetail()
    } 
  },

  /**
   * 红包领取详情
   */
  loadRedPacketDetail: function() {
    let that = this;
    service.getGroupbuypacketdetail(this.data.groupBuyUserId,
      function(data) {
        // 如果有数据，说明有未拆的红包，不走开团参团的逻辑
        if (data) {
          that.setData({
            redPacketData: data
          })
        } else {
          that.loadData();
        }
      },
      function(error) {
        that.loadData();
        if (error) {
          wx.showToast({
            title: error,
            icon: 'none'
          });
        }
      }
    )
  },

  /**
   * 初始化数据
   */
  loadData: function() {
    var self = this;
    this.getGroupList(function(isOpen) {
      if (isOpen == 0) {
        service.confirmGroupRedPacket(self.data.groupBuyId, self.data.addressId,
          function(res) {
            console.log(res);
            self.setData({
              groupBuyId: res.groupBuyId,
              groupBuyUserId: res.groupBuyUserId,
            })
            self.getGroupDetailNew();
          },
          function(res) {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 3000,
            });
            self.setData({
              inviteUserId: app.globalData.userId
            });
          });
      } else {
        self.getGroupDetailNew();
      }
    })
  },
  /**
   * 查询拼团红包列表（数量为1）
   */
  getGroupList: function(callBack) {
    var self = this;
    service.getGroupList(self.data.inviteUserId, 2, function(res) {
      var groupBuyGoodsVos = [];
      if (res.groupBuyGoodsVos.length < 1) {
        return;
      } else {
        groupBuyGoodsVos = res.groupBuyGoodsVos[0]
        let groupBuyId = groupBuyGoodsVos.groupBuyId;
        // 开团成功后，立即查询列表的groupBuyUserId可能为空
        let groupBuyUserId = groupBuyGoodsVos.groupBuyUserId;
        let addressId = 84;
        self.setData({
          groupBuyGoodsVos: groupBuyGoodsVos,
          groupBuyId: groupBuyId,
          groupBuyUserId: groupBuyUserId,
          addressId: addressId
        })
        // groupBuyUserId为空说明未开团
        if (!self.data.groupBuyUserId) {
          callBack(0);
          return;
        }
        callBack(1)
      }
    }, function (err) {
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 3000,
      });
    });
  },
  //获取分享信息
  getShareMessage: function(type) {
    var self = this;
    utilService.shareSettings(type,
      function(data) {
        console.log("分享数据", data)
        self.setData({
          shareMsg: data
        })
      },
      function(error) {

      }
    );
  },

  /**
   * 提交表单
   */
  submitForm: function(e) {
    // 获取表单id
    let formId = e.detail.formId;
    getApp().saveUserFormId(formId, 22);
  },

  /** 
    GROUP_RED_PACKET_EXEIST(16001, "您已开团，无法加入"),
    GROUP_RED_PACKET_ENOUGH(16002, "每天仅可开团X次，请明日再来哦！"),
    GROUP_RED_PACKET_NOT_BEGIN(16003, "还未到开团时间，请稍等！"),
    GROUP_RED_PACKET_NOT_NEW(16005, "您已不是新用户，快去开团吧！"),
    GROUP_RED_PACKET_OVER(16006, "该团已拼成，自己开团拿现金吧！"),
    GROUP_RED_PACKET_NOT_RECEIVE(16007, "红包已被您领取，自己开团拿现金吧！"),
    GROUP_RED_PACKET_RECEIVE_NOT(16008, "您还有红包未领取，先拿现金吧！"),
   */

  /**
   * 开团
   */
  openGroup: function() {
    let self = this;
    service.confirmGroupRedPacket(this.data.groupBuyId, this.data.addressId,
      function(res) {
        // 已经开团了，无法再次开团
        if (res.code && res.code != 200) {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 3000
          });
          return;
        }
        if (res.groupBuyUserId) {
          self.data.groupBuyUserId = res.groupBuyUserId;
          self.setData({
            groupBuyUserId: res.groupBuyUserId
          });
        }
        console.log(res);
        // 刷新数据
        self.getGroupDetailNew();
      },
      function(res) {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 3000
        });
      });
  },

  /**
   * 参团
   */
  joinGroup: function() {
    let self = this;
    service.helpGrouperRedPacket(this.data.groupBuyId, this.data.grouperId, this.data.groupBuyUserId,
      function(res) {
        if (res.code && res.code != 200) {
          self.setData({
            status: 1,
            reason: res.message,
            inviteUserId: app.globalData.userId
          });
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 3000,
          })
          return;
        }
        // 参团失败需要对groupBuyUserId赋值，可能需要重新开团
        self.loadRedPacketDetail();
      },
      function(res) {
        // 参团失败，已经开团
        if (res.data.code && res.data.code == 16001) {
          self.setData({
            reason: res.data.message,
            joinStatus: 1,
          });
        } else if (res.data.code && res.data.code == 16005) {// 不是新用户，去开团
          self.setData({
            reason: res.data.message,
            joinStatus: 2,
          });
        } else if (res.data.code && res.data.code == 16009) {// 团超时
          self.setData({
            reason: res.data.message,
            status: 2,
          });
        }
      });
  },

  /**
   * 拼团详情
   */
  getGroupDetailNew: function() {
    let self = this;
    // 已经开团 自己或别人是团长的情况
    // 查询拼团详情（状态）（0拼团中1拼团失败2拼团完成3参与4未参与）
    service.getGroupDetailNew(this.data.inviteUserId, this.data.groupBuyId, this.data.groupBuyUserId, 2, function(data) {
      let grouperId = data.grouperId;
      // 设置用户头像信息
      var items = data.userUrls;
      items.splice(0, 0, data.grouper)

      if (items.length > 1) {
        // 有参团人
        var sum = data.total - data.userUrls.length
        for (var i = 0; i < sum + 1; i++) { // +团长
          items.push('')
        }
      } else {
        // 没有参团人
        for (var i = 0; i < data.total; i++) {
          items.push('')
        }
      }
      self.setData({
        grouperId: data.grouperId,
        status: data.status,
        second: data.second,
        userUrls: data.userUrls,
        groupDetail: data,
        items: items,
      })
      // 已开团状态
      if (data.status == 0 || data.status == 3) {
        if (data.second > 0) {
          // 更新倒计时
          self.updateTime(data.second);
        }
      }
    });
  },

  /**
   * 更新倒计时
   */
  updateTime: function(totalSecond) {
    let self = this;
    if (this.data.timeCounting == true) {
      return;
    }
    this.setData({
      timeCounting: true,
    })
    var interval = setInterval(function() {
      // 秒数
      var second = totalSecond;
      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        this.setData({
          timeCounting: false,
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
        // 延迟两秒刷新
        setTimeout(function() {
          self.getGroupDetailNew();
        }, 1000);
      }
    }.bind(this), 1000);
  },

  /**
   * 点击活动规则
   */
  activityRuleClick: function(e) {
    wx.navigateTo({
      url: '/redPacket/pages/rankings/rankingRule/rankingRule?type=32',
    })
  },

  /**
   * 我的红包
   */
  myRedPacketClick: function(e) {
    wx.navigateTo({
      url: '/redPacket/pages/moneyRed/moneyRed',
    })
  },

  /**
   * 拆红包
   */
  openRedPacketClick: function(e) {
    var data = JSON.stringify(this.data.redPacketData)
    wx.redirectTo({
      url: '/redPacket/pages/openPacket/openPacket?data=' + data,
    })
  },

  /**
   * 再去开团
   */
  confirmGroupAgain: function(e) {
    if (this.data.joinStatus == 1){
      this.setData({
        inviteUserId: app.globalData.userId,
        joinStatus: 0
      })
      this.loadData()
    }else if(this.data.joinStatus == 2){
      this.setData({
        inviteUserId: app.globalData.userId,
        joinStatus: 0
      })
      this.openGroup();
    }else{
      if (this.data.status == 1){
        this.setData({
          inviteUserId: app.globalData.userId,
        })
        this.openGroup();
      }
    }
  },

  /**
   * 下一页
   */
  nextPageClick: function(e) {
    if (this.data.page * 4 + 1 <= this.data.items.length) {
      if (this.data.page > 1) {
        this.data.preShow = true
      } else {
        this.data.preShow = false
      }
      this.setData({
        preShow: this.data.preShow,
        nextShow: true,
        page: this.data.page + 1,
        scrollLeft: this.data.scrollLeft + this.data.scrollWidth
      });
    } else {
      this.setData({
        nextShow: true,
      });
    }
  },

  /**
   * 上一页
   */
  prePageClick: function(e) {
    if (this.data.page > 1) {
      this.setData({
        page: this.data.page - 1,
        preShow: true,
        scrollLeft: this.data.scrollLeft - this.data.scrollWidth
      });
    } else {
      this.setData({
        preShow: false
      });
    }
  },

  onScroll: function(e) {
    this.data.scrollLeft = e.detail.scrollLeft;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var self = this;
    var shareMsg = this.data.shareMsg;
    var title = shareMsg.title.replace(/#/, app.globalData.userInfo.nickName);
    title = shareMsg.title.replace(/{}/, this.data.groupDetail.goodsName);
    //TODO邀请好友
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    console.log("redPacket/pages/openGroup/openGroup?userId=" + app.globalData.userId + "&groupBuyUserId=" + self.data.groupDetail.groupBuyUserId + "&groupBuyId=" + self.data.groupBuyId + "&grouperId=" + self.data.groupDetail.grouperId + "&flag=1")
    return {
      title: this.data.shareMsg.title,
      path: "redPacket/pages/openGroup/openGroup?userId=" + app.globalData.userId + "&groupBuyUserId=" + self.data.groupDetail.groupBuyUserId + "&groupBuyId=" + self.data.groupBuyId + "&grouperId=" + self.data.grouperId + "&flag=1",
      imageUrl: this.data.shareMsg.pic,
      shareInfo: app.globalData.userInfo,
      success: function(res) {
        wx.showToast({
          title: "转发成功",
          icon: 'success',
          duration: 2000
        })
      },

      fail: function(res) {
        // 转发失败
        console.info("转发失败")
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadRedPacketDetail();
    setTimeout(function(res) {
      wx.stopPullDownRefresh();
    }, 2000);
  },
})